package cn.fl.institution.controller;

import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.*;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.customer.service.ICstNpBscInfoService;
import cn.fl.customer.vo.CstBscInfoVO;
import cn.fl.customer.vo.CstNpBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.api.IPrjCstAccInfoApiService;
import cn.fl.project.condition.PrjCstAccInfoQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.service.IPrjBscExtService;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjCstAccInfoService;
import cn.fl.project.vo.PrjBscExtVO;
import cn.fl.project.vo.PrjCstAccInfoVO;
import cn.fl.system.constant.SysInsCfgInfoConstant;
import cn.fl.system.service.ISysRegionService;
import com.alibaba.fastjson.JSONObject;
import fl.constant.facade.framework.constant.SystemConstant;
import fl.inf.facade.api.ITransLogApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Description: 项目基础信息表 控制层  众邦银行
 */
@Controller
@RequestMapping("/institution/zbbank")
public class PrjBscInfoInsZBController {

	private static final Logger logger = LoggerFactory.getLogger(PrjBscInfoInsZBController.class);

    @Autowired
    private IPrjBscInfoService prjBscInfoService; // 项目基础信息表

	@Autowired
	private IPrjCstAccInfoApiService prjCstAccInfoApiService; // 项目客户账户信息表
	
	@Autowired
	private ICstBscInfoService cstBscInfoService; // 客户基础信息
	
	@Autowired
	private ICstNpBscInfoService cstNpBscInfoService; // 自然人信息
	
	@Autowired
	private IPrjBscExtService prjBscExtService; //项目基础信息扩展表
	@Autowired
	private ISysRegionService sysRegionService;//查询省市县
	@Autowired
	private IPrjCstAccInfoService prjCstAccInfoService;//项目客户基础信息表

	@Autowired
	private ITransLogApi transLogApi;
	/**
	 * 保存 项目客户信息
	 */
	@SuppressWarnings("unused")
	@RequestMapping(value = "/save.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object save(Long prjId, HttpServletRequest request, HttpServletResponse response) throws BaseException {
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "四要素校验通过");
		 String rgnPrCdNm = ""; // 省名称
	     String rgnCyCdNm = ""; // 市名称
	     String rgnCountyNm ="";//县名称
		PrjBscExtVO prjBscExtVO = new PrjBscExtVO();//项目基础信息扩展
		CstNpBscInfoVO cstNpBscInfoVO = new CstNpBscInfoVO();//自然人客户基础信息
		PrjCstAccInfoQueryCondition prjCstAccInfoQC = new PrjCstAccInfoQueryCondition();//项目客户账户信息
		String cstId = request.getParameter("cstId"); // 客户ID
		String certValidSDt = request.getParameter("certValidSDt"); // 证件有效起始日期
		String certValidEDt = request.getParameter("certValidEDt"); // 证件有效终止日期
		String rgnProCd = request.getParameter("rgnProvCd"); // 区域-省
		String rgnCtCd = request.getParameter("rgnCityCd"); // 区域-市
		String rgnTwCd = request.getParameter("rgnCountyCd"); // 区域-县
		String monIncmYuan = request.getParameter("monIncmYuan"); // 月收入
		String bkCd = request.getParameter("bkCd"); //开户银行
		String bkNo = request.getParameter("bkNo"); //开户行号
		String accNo = request.getParameter("accNo"); //银行账号
		String mp = request.getParameter("mp"); //手机号
		String cstNm = request.getParameter("cstNm"); //账号名称
		String bkNm = request.getParameter("bkNm"); //开户银行名称
		if (StringUtils.isBlank(certValidEDt)) {
			return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护证件有效终止日期!");
		} else {
			if ((!DateUtils.isDate(certValidEDt, "yyyy-MM-dd"))
					&&(!certValidEDt.equals(PropertiesCacheUtils.getProperty(SystemConstant.CHECK_DATE_LONG)))) {
				return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护证件有效终止日期格式（yyyy-MM-dd 或 长期）！");
			}
		}
		if (!certValidEDt.equals(PropertiesCacheUtils.getProperty(SystemConstant.CHECK_DATE_LONG))) {
			Date startDate = DateUtils.formatStringToDate(certValidSDt, "yyyy-MM-dd");
			Date endDate = DateUtils.formatStringToDate(certValidEDt, "yyyy-MM-dd");
			if (DateUtils.equals(startDate, endDate) || DateUtils.after(endDate, startDate)) {
				return new DataResultVO(BaseConstant.IS_YESNO_NO, "证件有效起始日期 不能大于等于 证件有效终止日期！");
			}
		}
		// 身份证号码
				String certNo = null;
				String certTypCd = null;
				CstBscInfoVO cstBscInfoVO = this.cstBscInfoService.selectDetailById(Long.valueOf(cstId));
				if (null != cstBscInfoVO && StringUtils.isNotBlank(cstBscInfoVO.getCertNo())) {
					certNo = cstBscInfoVO.getCertNo(); // 证件号码
					 certTypCd = cstBscInfoVO.getCertTypCd();
				}
		try {
			if(StringUtils.isNotEmpty(prjId)){
				prjBscExtVO.setId(prjId);
			}
			if(StringUtils.isNotEmpty(rgnProCd)){
				prjBscExtVO.setRgnProCd(rgnProCd);
			}
			if(StringUtils.isNotEmpty(rgnCtCd)){
				prjBscExtVO.setRgnCtCd(rgnCtCd);
			}
			if(StringUtils.isNotEmpty(rgnTwCd)){
				prjBscExtVO.setRgnTwCd(rgnTwCd);
			}
			if(StringUtils.isNotEmpty(cstId)){
	   			cstNpBscInfoVO.setId(Long.valueOf(cstId));
	   		}
			if(StringUtils.isNotEmpty(certValidEDt)){
				cstNpBscInfoVO.setCertValidEDt(certValidEDt);
			}
			if(StringUtils.isNotBlank(certValidSDt)){
				cstNpBscInfoVO.setCertValidSDt(certValidSDt);
			}
			if(StringUtils.isNotBlank(monIncmYuan)){
				cstNpBscInfoVO.setYrInc(DecimalUtils.convertYuanToFen(DecimalUtils.mul(Double.valueOf(monIncmYuan), 12D)));
			}
			if(StringUtils.isNotBlank(bkCd)){
				prjCstAccInfoQC.setBkCd(bkCd);
			}
			if(StringUtils.isNotBlank(bkNm)){
				prjCstAccInfoQC.setBkNm(bkNm);
			}
			if(StringUtils.isNotBlank(cstNm)){
				prjCstAccInfoQC.setAccNm(cstNm);
			}
			if(StringUtils.isNotBlank(bkNo)){
				prjCstAccInfoQC.setBkNo(bkNo);
			}
			if(StringUtils.isNotBlank(accNo)){
				prjCstAccInfoQC.setAccNo(accNo);
			}
			if(StringUtils.isNotBlank(mp)){
				prjCstAccInfoQC.setMp(mp);
			}
			if(StringUtils.isNotBlank(cstNm)){
				prjCstAccInfoQC.setCstNm(cstNm);
			}
			prjCstAccInfoQC.setPrjId(Long.valueOf(prjId));
			prjCstAccInfoQC.setCstId(Long.valueOf(cstId));
			prjCstAccInfoQC.setCertNo(certNo);
			prjCstAccInfoQC.setCertTypCd(certTypCd);
			BaseLogUtils.info(logger, "save", "众邦立项保存 项目基本信息Strat： prjBscExtVO = " + JSONObject.toJSONString(prjBscExtVO));
			prjBscExtVO.setIsDel(0);
			if(StringUtils.isNotBlank(String.valueOf(prjId))){
				prjBscExtVO.setMdfTm(new Date());
				prjBscExtVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
			}else{
				prjBscExtVO.setCrtTm(new Date());
				prjBscExtVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			}
			this.prjBscInfoService.savePrjBscExt(prjBscExtVO);
			result.setData(prjBscExtVO);
			result.setSuccess(BaseConstant.IS_YESNO_YES);
			BaseLogUtils.info(logger, "save", "众邦立项保存 项目基本信息End： prjBscExtVO = " + JSONObject.toJSONString(prjBscExtVO));
			BaseLogUtils.info(logger, "save", "众邦立项保存 自然人客户信息Strat： cstNpBscInfoVO = " + JSONObject.toJSONString(cstNpBscInfoVO));
           CstNpBscInfoVO npBscInfoVO = this.cstNpBscInfoService.selectById(Long.valueOf(cstId));
           if(null != npBscInfoVO && StringUtils.isNotEmpty(npBscInfoVO.getId())){
        	   this.cstNpBscInfoService.modify(cstNpBscInfoVO);
        	 
           }else{
        	   this.cstNpBscInfoService.add(cstNpBscInfoVO);
           }
            result.setSuccess(BaseConstant.IS_YESNO_YES);
			BaseLogUtils.info(logger, "save", "众邦立项保存 自然人客户信息End： cstNpBscInfoVO = " + JSONObject.toJSONString(cstNpBscInfoVO));
			BaseLogUtils.info(logger, "save", "众邦立项保存 项目客户账户信息Strat： prjCstAccInfoQC = " + JSONObject.toJSONString(prjCstAccInfoQC));
			/*PrjCstAccInfoVO prjCstAccInfo = this.prjCstAccInfoService.selectByPrjId(prjId);
			Long prjCstAccid = null;
			if(null != prjCstAccInfo && null != prjCstAccInfo.getId()){
				prjCstAccid = prjCstAccInfo.getId();
				prjCstAccInfoQC.setId(prjCstAccid);
			}*/
            PrjCstAccInfoQueryCondition prjCstAccInfo = new PrjCstAccInfoQueryCondition();
            prjCstAccInfo.setPrjId(prjId);
            prjCstAccInfo.setIsDel(BaseConstant.IS_YESNO_NO);
            prjCstAccInfo.setInsCode(PrjBscInfoConstant.PRJ_INS_CODE_ZBBANK);
            List<PrjCstAccInfoVO> prjCstAccInfoVOS = this.prjCstAccInfoService.searchList(prjCstAccInfo);
            if (CollectionUtils.isNotEmpty(prjCstAccInfoVOS)) {
                PrjCstAccInfoVO prjCstAccInfoVO = prjCstAccInfoVOS.get(0);
                prjCstAccInfoQC.setId(prjCstAccInfoVO.getId());
            }
			// 众邦类型添加
			prjCstAccInfoQC.setInsCode(PrjBscInfoConstant.PRJ_INS_CODE_ZBBANK);
			DataResultDTO resultDTO = this.prjCstAccInfoApiService.modifyPrjAccInfo(prjCstAccInfoQC);
			String chkRstCd = null, rstDesc = null;
			String bankCardType = null;
			if(null != resultDTO && null != resultDTO.getData()){
				if(String.valueOf(BaseConstant.IS_YESNO_YES).equals(resultDTO.getCode())){
					@SuppressWarnings("unchecked")
					Map<String, String> ckResMap = (Map<String, String>) resultDTO.getData();
					chkRstCd = ckResMap.get("chkRstCd");
					rstDesc = ckResMap.get("rstDesc");
					bankCardType = ckResMap.get("bankCardType");
					if(chkRstCd.equals(SysInsCfgInfoConstant.CODE_CST_AUTH_RST_CD_1)){
						result.setSuccess(BaseConstant.IS_YESNO_YES);
						result.setInfo("四要素信息校验通过");
						if (!"0".equals(bankCardType)){  //
							result.setSuccess(BaseConstant.IS_YESNO_NO);
							result.setInfo("不支持此类银行卡，请更换为借记卡");
						}
					}else if(SysInsCfgInfoConstant.CODE_CST_AUTH_RST_CD_0.equals(chkRstCd) || SysInsCfgInfoConstant.CODE_CST_AUTH_RST_CD_2.equals(chkRstCd)){
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("四要素信息校验未通过");
					}
				}else{
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(resultDTO.getInfo());
				}
			}else{
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("众邦立项保存失败异常");
			}
				BaseLogUtils.info(logger, "save", "众邦立项保存 项目客户账户信息End： prjCstAccInfoQC = " + JSONObject.toJSONString(prjCstAccInfoQC));
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "save", "众邦立项保存失败 " + ex.getMessage());
			ex.printStackTrace();
		}
		catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo("保存失败!");
			BaseLogUtils.error(logger, "save", "众邦立项保存失败 " + ex.getMessage());
			ex.printStackTrace();
		}
		return result;
	}

}
